package com.qian.ddj.web.controller;


import com.qian.api.ddj.model.User;
import com.qian.api.ddj.service.IUserService;
import com.qian.api.ddj.util.RandomUtils;
import com.qian.api.ddj.util.SmsUtils;
import com.qian.ddj.utils.UserUtils;
import com.yaowk.api.common.BaseException;
import com.yaowk.web.system.security.SecurityUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/ddj/messageCheckCode")
@RestController
@Api(tags = "短信验证码接口")
public class MessageCheckCodeController {

    @Autowired
    private IUserService userService;

    @PostMapping("/send")
    public void send(String phone){
       String code =  RandomUtils.getRandNum(6);
        System.out.println("验证码："+code);
        SmsUtils.sendSms(phone,code);
       UserUtils.messageCheckCodeMap.put(phone,code);

    }

    @PostMapping("/check")
    public void check(String phone,String code){
        if (UserUtils.messageCheckCodeMap.get(phone).equals(code)){
            User user = userService.findById(SecurityUtils.getUserId());
            user.setPhone(phone);
            UserUtils.messageCheckCodeMap.remove(phone);
            return;
        }
        throw new BaseException("验证码错误！");
    }

    @PostMapping("/user")
    public void userSend(){
        User user = userService.findById(SecurityUtils.getUserId());
        if (!StringUtils.isEmpty(user.getPhone())){
            String code =  RandomUtils.getRandNum(6);
            System.out.println("验证码："+code);
            SmsUtils.sendSms(user.getPhone(),code);
            UserUtils.messageCheckCodeMap.put(user.getPhone(),code);
            return;
        }
        throw new BaseException("您未绑定手机！");
    }

    @PostMapping("/userCheck")
    public void userCheck(String code){
        User user = userService.findById(SecurityUtils.getUserId());
        if (UserUtils.messageCheckCodeMap.get(user.getPhone()).equals(code)){
            UserUtils.messageCheckCodeMap.remove(user.getPhone());
            return;
        }
        throw new BaseException("验证码错误！");
    }


}
